exutils = require('express/lib/utils')
ck = require('coffeekup')
fs = require("fs")
path = require "path"
crypto = require "crypto"
assert = require "assert"
buffer = require "buffer"
md = require("node-markdown").Markdown
rq = require "request"
geoip = require "geoip-lite"
connect_utils = require("connect").utils

utils = module.exports =
  ct_convert: do ()->
    ct_item = fs.readFileSync("views/ct_item.coffee", "utf-8")
    (ct)->
      content = md(exutils.escape(ct.ct))
      ct["ct"] = content.replace(/[\n\r]+/g, ((n)->
        return (str)->
          if --n > 0 then "<br />" else ""
      )(5))
      ck.render(ct_item, ct)

  ip2adr: (ip)->
      geoip.lookup ip

  sha1: ()->
    shasum = crypto.createHash "sha1"
    for i in arguments
      shasum.update i
    shasum.digest "hex"

  sha256 : () ->
    hash = crypto.createHash('sha256')
    for i in arguments
      hash.update i
    hash.digest "hex"
      
  hmac_sha1: (str, salt)->
    shasum = crypto.createHmac "sha1", salt
    shasum.update str
    shasum.digest "hex"

  sendmail: do()->
    postageapp = require('postageapp')('LLyi7NWbHHcXbZC02U0oCROtIyZfPmjc')
    (d)->
      assert.ok d.recipients, "Must has email to address"
      assert.ok d.content, "Must has email content"
      postageapp.sendMessage d

  mkdirs : (dirpath, callback)->
    path.exists dirpath, (exists)->
      if exists
        callback(dirpath)
      else
        utils.mkdirs path.dirname(dirpath), ()->
          fs.mkdir dirpath, callback

  to_base64 : (str, encoding="utf8")->
    return (new Buffer(str, encoding)).toString("base64")

  to_str : (str, encoding="base64")-> #ascii, utf8, ucs2, base64, binary, hex
    return (new Buffer(str, encoding)).toString("utf8")

  rand: (min=10, max=min)->
    if min == max
      Math.random()*min | 0
    else
      assert.ok min < max, "min(#{min}) MUST less then max(#{max})"
      min + Math.random()*(max-min) | 0

  randstr: do ()->
    tmp = (String.fromCharCode i for i in [65..122] when i not in [91..96])
    tmplen = tmp.length
    (min=5, max=min)->
      if min == max
        (tmp[Math.random()*tmplen | 0] for i in [0..min]).join("")
      else
        assert.ok min < max, "min MUST less then max"
        (tmp[Math.random()*tmplen | 0] for i in [min..(min + helper.rand(max-min))]).join("")

  merge: connect_utils.merge

  cache: (becache)->
    cache = undefined
    (destroy, callback)->
      if typeof(destroy) == "function"
        callback = destroy
        destroy = false
      
      if cache is not undefined and destroy
        becache (ret)->
          cache = ret
          callback cache
      else
        callback cache

if require.main == module
  do()-> #ip2adr
    assert.equal utils.ip2adr("199.119.200.229").city, 'Walnut'
    #console.log utils.ip2adr "123.121.5.193"

  do()-> #sha1
    assert.equal utils.sha1("123"), "40bd001563085fc35165329ea1ff5c5ecbdbbeef"

  do()-> #sendmail
    if false #默认不测试
      utils.sendmail
        recipients: "aisk1988@gmail.com"
        content:
          "text/html": "您的吐槽网帐号已经开通: Aisk<br />请尽快去登录.<br /><a href='http://tucao.in/active/51m6b2/>激活</a>"
          "text/plain": "您的吐槽网帐号已经开通: Aisk<br />请尽快去登录.<br /><a href='http://tucao.in/active/51m6b2/>激活</a>"
        subject: "Tucao.in"
        from: "men@tucao.in"

  do()-> #mkdirs
    d = "" + ((new Date()).getTime() | 0)
    dirpath = "/tmp/#{d[...4]}/#{d[4..]}"
    utils.mkdirs dirpath, (r)->
      assert.ok path.existsSync dirpath
